package com.ruoyi.web.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.business.UserWxInfo;
import com.ruoyi.business.service.UserService;
import com.ruoyi.business.service.WechartService;
import com.ruoyi.common.common.ResultBody;
import com.ruoyi.common.exception.BizException;
import com.ruoyi.common.utils.AesException;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @title: WechartController
 * @copyright: copyright (c) 2021
 * @author: jiangguanjun
 * @date: 2023/2/7 12:15
 * @firstReview:
 * @lastReview:
 * @desc:
 */
@RestController
@Slf4j
@Api(value = "WechartController", tags = "微信相关，暂时不联调，后台做测试用的")
public class WechartController {


    @Autowired
    private WechartService wechartService ;

    @Autowired
    private UserService userService ;

    @Autowired
    private RestTemplate restTemplate ;

    @GetMapping("/wx/token")
    public String getAccessToken(){
        return wechartService.getAccessToken() ;
    }

    /**
     * 微信验证token
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping(value = "/wx",produces = "text/html;charset=utf-8")
    public String wx(@RequestParam("signature") String signature,@RequestParam("timestamp") String timestamp,
                             @RequestParam("nonce") String nonce,@RequestParam("echostr") String echostr) {
        log.info("signature:::{},timestamp::::{},nonce::::{},echostr::::{}",signature,timestamp,nonce,echostr);


        //排序
        String[] arr = {"lBRgXbEcfEQzh6NPYD", timestamp, nonce};
        Arrays.sort(arr);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        //sha1Hex 加密
        MessageDigest md = null;
        String temp = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            temp = byteToStr(digest);
            log.info("加密后的token:"+temp);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if ((temp.toLowerCase()).equals(signature)){
            return echostr;
        }
        return null;
    }

    /**
     * 微信事件处理
     * @return
     */
    /*@PostMapping(value = "/wx",produces = "application/text;charset=UTF-8")
    public String wxPost(HttpServletRequest request) throws InterruptedException, AesException, DocumentException {

        return wechartService.process(request) ;
    }*/



    /**
     * @author jiangguanjun
     * @date 2023/2/14 20:55
     * @param
     * @return
     * @desc 设置菜单 格式： {
     *      "button":[
     *      {
     *           "type":"click",
     *           "name":"今日歌曲",
     *           "key":"V1001_TODAY_MUSIC"
     *       },
     *       {
     *            "name":"菜单",
     *            "sub_button":[
     *            {
     *                "type":"view",
     *                "name":"搜索",
     *                "url":"http://www.soso.com/"
     *             },
     *             {
     *                  "type":"miniprogram",
     *                  "name":"wxa",
     *                  "url":"http://mp.weixin.qq.com",
     *                  "appid":"wx286b93c14bbf93aa",
     *                  "pagepath":"pages/lunar/index"
     *              },
     *             {
     *                "type":"click",
     *                "name":"赞一下我们",
     *                "key":"V1001_GOOD"
     *             }]
     *        }]
     *  }
     */
    @CrossOrigin
    @PostMapping(value = "/setMenu")
    public ResultBody<String> setMenu(@RequestBody JSONObject jsonObject) {
       log.info("jsonObject:::{}",jsonObject.toJSONString());
       String accessToken = getAccessToken() ;
       String deleteNenuRul = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+accessToken ;
        HttpHeaders httpHeaders = new HttpHeaders() ;
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String req = jsonObject.toJSONString() ;
        HttpEntity httpEntity = new HttpEntity(req,httpHeaders) ;
        String res = restTemplate.getForObject(deleteNenuRul,String.class) ;
        log.info("删除菜单结果：：：：{}",res);

       String createUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+accessToken ;
        res = restTemplate.postForObject(createUrl,httpEntity,String.class) ;
      /*  HttpHeaders httpHeaders = new HttpHeaders() ;
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String req = jsonObject.toJSONString() ;
        HttpEntity httpEntity = new HttpEntity(req,httpHeaders) ;*/


        return ResultBody.success(res) ;

    }

    @PostMapping(value = "/getUserCode")
    public ResultBody wx(@RequestBody JSONObject jsonObject) {
        String code =  jsonObject.getString("code") ;
        log.info("得到的用户code:::{}",code);

        /*log.info("开始获取用户accessToken");
        String getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx8431359f8fa41916&secret=e2beaf71471610ef49a13f483027dec1&code="+code+"&grant_type=authorization_code" ;
        String res = restTemplate.getForObject(getAccessTokenUrl, String.class) ;
        log.info("获取用户access_token完毕：access_token::::{}",res);

        UserAccessTokenInfo userAccessTokenInfo = JSONObject.parseObject(res,UserAccessTokenInfo.class) ;
        log.info("开始获取用户信息");
        String userInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+userAccessTokenInfo.getAccess_token()+"&openid="+userAccessTokenInfo.getOpenid()+"&OPENID&lang=zh_CN" ;


        String userInfoStr = restTemplate.getForObject(userInfoUrl,String.class) ;
        log.info("用户基本信息：：{}",userInfoStr);

        UserWxInfo userWxInfo = JSONObject.parseObject(userInfoStr,UserWxInfo.class) ;
        log.info("获取用户信息完毕 ：{}",userInfoStr);

        return userService.saveOrUpdate(userWxInfo)  ;*/

        String appId = "wx8431359f8fa41916";
        String appSecret = "e2beaf71471610ef49a13f483027dec1";



        // 获取access_token的URL
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";

        // 发送GET请求获取access_token
        String res = restTemplate.getForObject(accessTokenUrl, String.class) ;
        log.info("res:::{}",res);
        // 解析返回的JSON数据
        JSONObject resultJson = JSONObject.parseObject(res.toString());

        if (resultJson.containsKey("errcode")) {
            // 错误处理
            throw new BizException() ;
        } else {
            String accessToken = resultJson.getString("access_token");
            log.info("accessToken::::{}",accessToken);
            String openid = resultJson.getString("openid");



            // 获取用户信息的URL
            String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=" + accessToken +
                    "&openid=" + openid +
                    "&lang=zh_CN";

            // 发送GET请求获取用户信息
            log.info("请求地址：：：：{}",userInfoUrl);
            String userInfoStr = restTemplate.getForObject(userInfoUrl,String.class) ;
            log.info("用户基本信息：：{}",userInfoStr);
            UserWxInfo userInfoJson = JSONObject.parseObject(userInfoStr,UserWxInfo.class) ;
            log.info("获取用户信息完毕 ：{}",userInfoStr);

            // 获取用户是否关注
             String Acc = getAccessToken() ;
            log.info("acc：：：：：：：：{}",Acc);
            String subURL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ Acc+"&openid="+openid+"&lang=zh_CN" ;
            String subRes = restTemplate.getForObject(subURL,String.class) ;
            log.info("subRes::::{}"+subRes);
            UserWxInfo subInfo = JSONObject.parseObject(subRes,UserWxInfo.class) ;
           // return userService.saveOrUpdate(userInfoJson) ;
            userInfoJson.setSubscribe(subInfo.getSubscribe());
            return ResultBody.success(userInfoJson) ;
        }
    }

    private static String byteToStr(byte[] byteArray){
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private static String byteToHexStr(byte mByte){
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4)& 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

}
